<template>
 <div>
 	<div class="top">
 		<el-row>
		  <el-col :span="12">
		  	<!--试题分类-->
		  	<el-autocomplete
      			class="inline-input"
		        v-model="checkTestClassify"
		        :fetch-suggestions="querySearch"
		        placeholder="请添加或选择试题分类"
		        @select="handleSelect"
		    >
		     <template slot-scope="{ item }">
			    <div class="name">{{ item }}</div>
			    <!--<span class="addr">{{ item.address }}</span>-->
			  </template>
		    </el-autocomplete>
		    
		    <!--试题类型-->
			<el-dropdown  @command = "questionTypeCheck" style="z-index: 100000;">
			  <el-button plain >
			    {{questionTypeIn? questionTypeIn.describ : '请选择试题类型'}}<i class="el-icon-arrow-down el-icon--right"></i>
			  </el-button>
			  <el-dropdown-menu slot="dropdown">
			    <el-dropdown-item v-for="item in questionType" :command="JSON.stringify(item)">{{item.describ}}</el-dropdown-item>
			  </el-dropdown-menu>
			</el-dropdown>
			<!--试题难度-->
			<el-dropdown style="margin-right: 20px;" @command = "levelCheck">
			  <el-button plain>
			    试题难度:{{levelIn}}<i class="el-icon-arrow-down el-icon--right"></i>
			  </el-button>
			  <el-dropdown-menu slot="dropdown">
			    <el-dropdown-item command="简单">简单</el-dropdown-item>
			    <el-dropdown-item command="普通">普通</el-dropdown-item>
			    <el-dropdown-item command="困难">困难</el-dropdown-item>
			  </el-dropdown-menu>
			</el-dropdown>
			
			<!--试题分值-->
			<!--请输入试题分值：<el-input-number size="small" style="width:150px;margin-left: 10px;" placeholder="请输入试题分值" v-model="inputScore"></el-input-number>
			<span style="color:red;">*</span>-->
		  </el-col>
		  <el-col v-if="!edition" :span="12" >
		  	<el-row type="flex" class="row-bg" justify="end">
			  	<el-button type="primary" @click="clearAll">重置</el-button>
 				<el-button type="warning" @click="addText">录入</el-button>
			</el-row>
		  </el-col>
		</el-row>
 	</div>
 	<div class="content" >
 		<div class="title" style="margin-top: 40px;">
 			<inPanelTitle tipdesc="题干" introdesc="这里填写题目描述"></inPanelTitle>
 			<editor  :active="{name:'title',value:active.title}" :baseheight="85" :clear="Editorclear" name="title" @childChangState="childChangState" @allEditorData="allEditorData"></editor>
 		</div>
 		<!--单复选框部分数据-->
 		<div v-if="!questionTypeIn.type ||questionTypeIn.type == 'single_choice' || questionTypeIn.type == 'multi_choice'" class="center_check_radio" style="margin-top: 40px;">
 			<inPanelTitle tipdesc="选项" introdesc=" 单/多选题的选项范围从 2 到 8 "></inPanelTitle>
 			<el-row>
 				<el-col v-for="(item,index) in radioList" :offset="1" :span="22" class="check_item" >
 					<div class="radio_list"> 
 						<div class="icon" style="cursor: pointer;" @click="check_In(questionTypeIn.type,index)">
	 						<img v-if="radio_check_list !== index && (questionTypeIn.type == 'single_choice' || !questionTypeIn)" src="../../../assets/images/radio-checked.png" style="width: 20px;height: 20px;margin-right: 5px;"/>
	 						<img v-if="radio_check_list === index && (questionTypeIn.type == 'single_choice' || !questionTypeIn)" src="../../../assets/images/radio-checked-check.png" style="width: 20px;height: 20px;margin-right: 5px;"/>
	 						<img v-if="muliti_check_list[index]==='true' && (questionTypeIn.type == 'multi_choice')" src="../../../assets/images/check_yes_fill.png" style="width: 20px;height: 20px;margin-right: 5px;"/>
	 						<img v-if="muliti_check_list[index]!=='true' && (questionTypeIn.type == 'multi_choice')" src="../../../assets/images/check_no.png" style="width: 20px;height: 20px;margin-right: 5px;"/>
 						</div> 
 						<editor :active="{name:'checkradio'+index,value:active['checkradio'+index]}" :clear="Editorclear" :baseheight="35" :name="'checkradio'+index" @childChangState="childChangState" @allEditorData="allEditorData"></editor>
 					</div>
 					<div class="remove" @click="deleteRadio(index,questionTypeIn.type)" v-if="index>1">
 						<i class="fa fa-remove fa-lg"></i>
 					</div>
 				</el-col>
 			</el-row>
 			<div class="add_icon" @click="addList" v-if="radioList.length<8">
 				<i class="fa fa-plus fa-lg" style="transform: translateY(1px);"></i>
 				<span>添加一个选项</span>
 			</div>
 		</div>
 		
 		<!-- 判断题  -->
 		<div class="judge" v-if="questionTypeIn.type == 'check'" style="margin-top: 40px;">
 			<inPanelTitle tipdesc="选项" introdesc=" 选择正确或者错误（默认正确） "></inPanelTitle>
 			<el-radio-group style="margin-top: 10px;" size="medium" v-model="judgeCheck">
		      <el-radio-button label="正确"></el-radio-button>
		      <el-radio-button label="错误"></el-radio-button>
		    </el-radio-group>
 		</div>
 		
 		
 		<!--填空题-->
 		<div class="fill" v-if="questionTypeIn.type == 'fill'" style="margin-top: 40px;">
 			<inPanelTitle tipdesc="参考" introdesc="请添加填空题的参考字段"></inPanelTitle>
 					<div v-for="(item,index) in fillList" class="el-input__inner">
 						<el-tag closable @close="fillRemove(index)">{{item}}</el-tag>
 					</div>
 			<el-input v-if="fillList.length<6" style="margin:10px 0px 10px 48px; width: 95%;" v-model="fill_input" placeholder="请输入内容"></el-input>
 			<div class="add_icon" @click="addFillList" v-if="fillList.length<6">
 				<i class="fa fa-plus fa-lg" style="transform: translateY(1px);"></i>
 				<span>添加一个选项</span>
 			</div>
 		</div>
 		
 		<!-- 简答题  -->
 		<div class="brief" v-if="questionTypeIn.type == 'brief'" style="margin-top: 40px;">
 			<inPanelTitle tipdesc="参考" introdesc="这里填写题目描述"></inPanelTitle>
 			<editor  :active="{name:'brief',value:active.brief}" :baseheight="85" :clear="Editorclear" name="brief" @childChangState="childChangState" @allEditorData="allEditorData"></editor>
 		</div>
 		
 		
 		<!--音频题-->
 		<div class="audio" v-if="questionTypeIn.type == 'audio'" style="margin-top: 40px;">
 			<inPanelTitle tipdesc="答案" introdesc="这里填写题目描述"></inPanelTitle>
 			<editor  :active="{name:'audio',value:active.audio}" :baseheight="85" name="audio" :clear="Editorclear" @childChangState="childChangState" @allEditorData="allEditorData"></editor>
 		</div>
 		
 		
 		<div class="analysis" style="margin-top: 40px;">
 			<inPanelTitle tipdesc="解析" introdesc="这里填写对应的答案解析"></inPanelTitle>
 			<editor  @click="analysisClick" :active="{name:'analysis',value:active.analysis}" :clear="Editorclear" :baseheight="85" name="analysis"  @childChangState="childChangState" @allEditorData="allEditorData"></editor>
 		</div>
 		
 		<div v-if="edition" style="width: 100%;margin: 20px 0;text-align: center;">
 			<el-switch
				v-model="is_vaild"
				active-text="此题有效"
				inactive-text="此题无效">
			</el-switch>
			<br />
			<br />
			<el-button @click="addText" type="warning" size="small">保存编辑</el-button>
 		</div>
 	</div>
 </div>
</template>

<script>
  import { questionDelete,questionGetType,questionUpdate,Login} from '@/assets/util/api.js'
  import E from 'wangeditor'
  export default {
    data() {
      return {
      	access_token:"",
      	checkTestClassify:"",//试题分类
      	restaurants:[],//试题分类搜索建议
      	questionType:"",//试题类型 单选 多选 判断  其他类型
      	levelIn:"普通",//试题难度
      	questionTypeIn:"",//选中试题类型以及描述
      	active:{'title':{'state':true,'value':""},'analysis':{'state':false,'value':""},"checkradio0":{'state':false,'value':""},"checkradio1":{'state':false,'value':""},"checkradio2":{'state':false,'value':""},"checkradio3":{'state':false,'value':""},'audio':{'state':false,'value':""},'brief':{'state':false,'value':""},'fill':{'state':false,'value':""}},//管理显示框框按钮
      	radio_check_list:"",//单选选中列表
      	radioList:["","","",""],//单选添加框列表
      	muliti_check_list:['false','false','false','false',],
      	all_edtor_data:[],//当前所有编辑框的数据
      	//判断题
      	judgeCheck:"正确",
      	//填空题
      	fill_input:"",
      	fillList:[],
      	//edition
      	edition:false,
      	Editorclear:false,
      	is_vaild:true,
      };
    },
    components:{
    	inPanelTitle:(resolve)=>require(["@/components/testQuestion/addItemBank/plugin/inPanelTitle"], resolve),
    	editor:(resolve)=>require(["@/components/testQuestion/addItemBank/plugin/Edition"], resolve),
    },
    watch:{
    	active:{
    		handler(val){
//	    		console.log("1111watch",val)
	    	},
	    	deep:true
    	},
    	'$route' (to, from) {
    		if(this.$route.query.type){
    			this.edition = true;
    			this.getEditionData();
    		}else{
    			this.edition = false
    		}
    	},
    	questionTypeIn(val){console.log(val);}
    },
    mounted(){
    	this.questionType = this.inStorage("get","questionType");
    	this.access_token = this.inStorage("get","access_token");
    	if(this.$route.query.type){
    		this.edition = true;
    		this.getEditionData();
    	}else{
    		this.edition = false
    	}
    },
    computed:{
    	
    },
    methods: {
     getEditionData(){
     	this.clearAll();
     	var type = this.inStorage("get","editor");
     	console.log(type)
     	this.checkTestClassify = type.pid;//试题分类
     	this.questionTypeIn = {type:type.bundle_t,describ:type.bundle}//题目类型
     	this.levelIn = type.difficulty ||"普通";//题目难度
     	this.$set(this.active.title,"value",type.title);
     	this.$set(this.active.analysis,"value",type.analysis);
     	type.is_vaild == 1 ? this.is_vaild = true : this.is_vaild = false;
     	this.quest_no = type.quest_no;
     	switch (type.bundle_t)
	       	{
	       		case 'single_choice': 	
	       		this.radio_check_list = parseInt(type.answer[0]);
	       		this.radioList = [];
	       		var content = JSON.parse(type.content);
	       		for(let i = 0;i<content.length;i++){
	       			this.$set(this.active['checkradio'+i],"value",content[i]);
	       			this.radioList.push("");
	       		}
	       		this.editionGetAllData();
		       		break;
		       	case 'multi_choice': 
		       	this.muliti_check_list = type.answer;
		       	this.radioList = [];
		       	var content = JSON.parse(type.content);
	       		for(let i = 0;i<content.length;i++){
	       			this.$set(this.active['checkradio'+i],"value",content[i]);
	       			this.radioList.push("");
	       		}
	       		this.editionGetAllData();
		       		break;
		       	case 'check': 
		       	this.judgeCheck = type.answer[0];
		       	this.editionGetAllData();
		       		break;
		       	case 'fill': 	
		       	this.fillList = type.answer;
		       	this.editionGetAllData();
		       		break;
		       	case 'brief': 	
		       	this.$set(this.active.brief,"value",type.content);
		       	this.editionGetAllData();
		       		break;
		       	case 'audio': 	
		       	this.$set(this.active.audio,"value",type.content);
		       	this.editionGetAllData();
		       		break;
		       	default :
		      	break;
	       	}
     	
     },
     editionGetAllData(){
     	var _this = this;
     	for(let i in _this.active){
     		_this.all_edtor_data.push({data:_this.active[i].value,name:i})
     	}
     	console.log("chushihua",_this.all_edtor_data)
     },
     querySearch(queryString, cb) {
        var restaurants = this.restaurants;
		var _this = this;
        var params = {
        	access_token:this.access_token
        }
        var arr = [];
        questionGetType(this,params).then((res)=>{
        	arr = res.data.data;
        	var result = queryString ? arr.filter(_this.createFilter(queryString)) : arr;
        	cb(result);
        })
      },
      createFilter(queryString) {
        return (restaurant) => {
          return (restaurant.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
      handleSelect(item) {
        this.checkTestClassify = item;
      },
        //获取试题难度
       levelCheck(e){
       	this.levelIn = e;
       },
       //获取试题类型以及描述
       questionTypeCheck(e){
       	this.questionTypeIn = JSON.parse(e);
       	this.all_edtor_data = [];
       },
       activeChange(){
       	this.active = !this.active
       },
       //编辑框状态改变
       childChangState(val){
       	var _this = this;
       	this.Editorclear = false;
       	for(let i in _this.active){
       		if(i == val.name){
       			_this.active[i].state = true;
       		}else{
       			_this.active[i].state = false;
       		}
       	}
       	_this.active = Object.assign({}, _this.active);
       },
       addText(){
       	var _this = this;
	    _this.active = Object.assign({}, _this.active);
	    setTimeout(function(){
	    	switch (_this.questionTypeIn.type)
	       	{
	       		case 'single_choice': 	
	       			let arr =[];
	       			arr.push(_this.radio_check_list.toString());
	    			if(!_this.radio_check_list && _this.radio_check_list !== 0){
	    				_this.$message.error("请选择答案");
	    				return;
	    			}
		       		_this.questionUpdate("single_choice",arr);
		       		break;
		       	case 'multi_choice': 	
		       	let mulitiListcheck = 0;
		       	_this.muliti_check_list.forEach(function(str,idx,arr){
		       		if(str === 'true'){
		       			++mulitiListcheck
		       		}
		       	})
		       	if(mulitiListcheck<=1){
		       		_this.$message.error("多选题答案至少为两个！");
	    			return;
		       	}
		       	_this.questionUpdate("multi_choice",_this.muliti_check_list);
		       		break;
		       	case 'check': 
//		       	if(this.judgeCheck){
//		       		_this.$message.error("判断题不可没有答案！");
//	    			return;
//		       	}
				let judgeCheck = [];
				judgeCheck.push(_this.judgeCheck);
		       	_this.questionUpdate("check",judgeCheck);
		       		break;
		       	case 'fill': 	
		       	if(_this.fillList.length<1){
		       		_this.$message.error("请输入填空题答案！");
	    			return;
		       	}
		       	_this.questionUpdate("fill",_this.fillList);
		       		break;
		       	case 'brief': 	
		       	_this.questionUpdate("brief");
		       		break;
		       	case 'audio': 	
		       	_this.questionUpdate("audio");
		       		break;
		       	default :
		       	let arr1 =[];
	       		arr1.push(_this.radio_check_list.toString());
	    		if(!_this.radio_check_list && _this.radio_check_list !== 0){
	    			_this.$message.error("请选择答案");
	    			return;
	    		}
		       	_this.questionUpdate("single_choice",arr1);
		       	break;
	       	}
	    },500)
       	
       },
       //添加或更新一个题目
       questionUpdate(type,answer){
       	var _this = this;
       	let title = ""
       	let analysis = ""
       	let content = [];
//     	if(!this.inputScore){
//     		this.$message.error("请输入试题分值！");
//     		return;
//     	}
//     	console.log("整个字段参数",this.all_edtor_data);
       	this.all_edtor_data.forEach((str,idx,arr)=>{
       		if(str.name === "title"){
       			if(str.data === "<p><br></p>"){
       				this.$message.error("标题不可为空！");
       				return;
       			}else {
       				title = str.data;
       			}
       			
       		}
       		if(str.name === "analysis"){
       			if(str.data === "<p><br></p>"){
       				analysis = ""
       			}else {
       				analysis =  str.data;
       			}
       		}
       		if(str.name === "brief" || str.name === "audio"){
       			if(str.data == "<p><br></p>"){
       				content = ""
       			}else {
       				content =  str.data;
       			}
       		}
       		if(str.name != "analysis" && str.name != "title"){
       			if(this.questionTypeIn.type === ""|| this.questionTypeIn.type=== undefined || this.questionTypeIn.type === 'single_choice' || this.questionTypeIn.type === 'multi_choice' ){
	       			let end = str.name.charAt(str.name.length-1);
	       			content[end] = str.data;
	       		}
       		}
	    })
       	if(typeof content != 'string'){
       		content = JSON.stringify(content);
       	}
       	let is_vaild_num = 1;
       	if(this.is_vaild === true){
       		 is_vaild_num = 1;
       	}else{
       		is_vaild_num = -1;
       	}
       	if(title == "" || title == "<p><br></p>"){
       		this.$message.error("标题不可为空");
       	}
       	var params = {
       		access_token:this.access_token,
       		quest_no:this.quest_no, //题目id
       		type:type,//题型
       		pid:this.checkTestClassify,//科目
       		title:title,//题目标题
       		content:content,//题目内容
       		picture:"",//题目图片
       		options:"",//题目选项
       		answer:answer,//题目答案
       		attach:"",//附加
       		full_score:this.inputScore,//满分值
       		limit_time:"",//答题限时
       		is_vaild:is_vaild_num,//是否有效 0是 -1否
       		difficulty:this.levelIn,//难度系数 简单/普通/困难
       		analysis:analysis,//题目解析
       	}
       		questionUpdate(this,params).then((res)=>{
	       		if(res.data.state == true){
	       			_this.clearAll();
	       			if(_this.edition == true){
	       				_this.$message.success("题目保存成功！");
	       				_this.RouterTo(_this,"/itemBank");
	       				_this.fillList = [];
	       				_this.inputScore = 0;
	       			}else{
	       				_this.$message.success("题目添加成功！");
	       			}
	       		}
       		})
       },
       //添加单选列表
       addList(){
       	var _this = this;
//     	if(this.questionTypeIn.type == 'single_choice'){
//     		
//     	}
//     	this.active['checkradio'+(this.radioList.length)].state = false;
       	_this.active = Object.assign({}, _this.active);
       	this.radioList.push("");
       	this.muliti_check_list.push('false');
       },
       //添加多选列表
       deleteRadio(index,type){
       		this.radioList.splice(index,1);
       		delete this.active['checkradio'+(index)];
       		if(type == 'multi_choice'){
	       		this.muliti_check_list.splice(index,1);
	       	}
       },
       //单选 多选 选中答案管理
       check_In(type,idx){
       	if(type == 'single_choice' || !type){
       		this.radio_check_list = idx;
       	}else if(type == 'multi_choice'){
       		if(this.muliti_check_list[idx] === 'false'){
       			this.muliti_check_list.splice(idx,1,'true');
       		}else{
       			this.muliti_check_list.splice(idx,1,'false');
       		}
       	}
       },
       //监听获取所有editor数据
       allEditorData(e){
	       	var _this = this;
	       	let editor_name = true;
	       	if(_this.all_edtor_data.length == 0){
	       		_this.all_edtor_data.push(e)
	       	}else{
	       		_this.all_edtor_data.forEach((str,idx,arr)=>{
	       			if(str.name == e.name){
						_this.active[str.name].value = e.data;			
	       				_this.all_edtor_data.splice(idx,1,e);
	       				editor_name = false;
	       				return;
	       			}
	       		})
	       		if(editor_name){
	       			_this.all_edtor_data.push(e);
	       		}
	       	}
       },
       //填空题
       addFillList(){
       	if(!!this.fill_input){
       		this.fillList.push(this.fill_input);
       		this.fill_input = "";
       	}
       },
       fillRemove(index){
       	this.fillList.splice(index,1);
       },
       clearAll(){
       	this.Editorclear = true;
       	let activeT = {}
       	for(let i in this.active){
       		this.$set(this.active[i],"value","")
       	}
        console.log("清理全部",this.active);
       }
    },
  }
 
</script>
<style lang="scss">
  .content{
  	padding:10px;
  	box-sizing: border-box;
  }
  .center_check_radio{
  	margin: 10px 0;
  	.check_item{
  		position: relative;
  		margin: 10px 0;
  	}
  	
  	.radio_list{
  		display: flex;
  		justify-content: flex-end;
  		align-items: center;
  		.edition{
  			width: 95%;
  		}
  	}
  	.remove{
  		display: inline-block;
  		width: 25px;
	    height: 25px;
	    background: #A9B3BF;
	    right: -35px;
	    z-index: 99999;
	    position: absolute;
	    top: 50%;
	    cursor: pointer;
	    margin-top: -9px;
	    text-align: center;
	    line-height: 20px;
	    color: #fff;
	    display: flex;
	    justify-content: center;
	    align-items: center;
	    .fa{
	    	margin-right: 0;
	    }
  	}
  }
  
  .add_icon{
  		background: #A9B3BF;
	    border-radius: 4px;
	    color: #fff;
	    padding: 10px 0;
	    margin-left: 48px;
	    width: calc(100% - 48px);
	    border:none;
	    cursor: pointer;
	    display: flex;
	    justify-content: center;
	    align-items: center;
  	}
  	.add_icon:focus{
  		box-shadow: 0 10px 10px 10px -10px #ffff;
  	}
  	.fill div.el-input__inner{
  		background-color: #EBEEF5;
  		border: 1px solid #EBEEF5;
  		width: 95%;
  		margin:5px 0px 5px 48px;
  	}
  	.fill .el-input__inner:hover{
  		border: 1px solid #EBEEF5;
  	}
</style>

